package br.com.lambdacore.ui.stripes.resolution;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.controller.StripesFilter;

import org.apache.commons.lang.StringUtils;

import br.com.lambdacore.ui.stripes.action.LambdaCoreAction;

public class PageResolution extends ForwardResolution {

	private LambdaCoreAction action;
	private String eventName;

	public PageResolution(LambdaCoreAction action) {
		super("");
		this.action = action;
		this.eventName = this.eventName();
	}

	public PageResolution(LambdaCoreAction action, String eventName) {
		this(action);
		this.eventName = eventName;
	}

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.setPath(this.jsp(this.eventName));
		super.execute(request, response);
	}

	private String actionName() {
		String urlBinding = StripesFilter.getConfiguration()
				.getActionResolver().getUrlBinding(this.action.getClass());
		return StringUtils.removeStart(urlBinding, "/action/");
	}

	private String eventName() {
		return this.action.getContext().getEventName();
	}

	private String getViewExtension() {
		return ".jsp";
	}

	private String getViewPath() {
		return "/WEB-INF/pages/";
	}

	private String jsp(String eventName) {
		String actionName = this.actionName();
		return new StringBuffer().append(this.getViewPath()).append(actionName)
				.append(eventName).append(this.getViewExtension()).toString();
	}

}
